<template>
  <div class="login">
    <div class="login-topBar">
      <top-bar></top-bar>
    </div>
    <div class="content">
      <div class="text">登录</div>
      <form>
        <el-row>
          <el-col :span="24">
            <div class="field">
              <!-- 自定义输入框的提示信息 -->
              <!-- 关闭拼写检查 -->
              <input
                required
                type="text"
                class="input"
                spellcheck="false"
                oninvalid="setCustomValidity('请先输入账号再登录')"
                oninput="setCustomValidity('')"
                v-model.trim="inputContent.inputUserName"
              />
              <!-- 使用trim修饰符会消除内容两端的空格，在输入空格的时候是不会出发数据的变化的 -->
              <span class="span">
                <!-- element-ui中i-con使用font-size设置 -->
                <i class="el-icon-user" style="font-size: 24px"></i>
              </span>
              <label class="label">请输入账号/邮箱</label>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="field">
              <!-- 关闭拼写检查 -->
              <input
                required
                type="password"
                class="input"
                spellcheck="false"
                oninvalid="setCustomValidity('请先输入密码再登录')"
                oninput="setCustomValidity('')"
                data="passworedtype"
                v-model.trim="inputContent.inputPassword"
              />
              <span class="span">
                <i class="el-icon-lock" style="font-size: 24px"></i>
              </span>
              <label class="label">请输入密码</label>
            </div>
          </el-col>
        </el-row>
        <!-- 设置验证码显示垂直居中 -->
        <el-row type="flex" align="middle">
          <el-col :span="14">
            <div class="field">
              <!-- 关闭拼写检查 -->
              <input
                required
                type="text"
                class="input"
                spellcheck="false"
                oninvalid="setCustomValidity('请先输入验证码再登录')"
                oninput="setCustomValidity('')"
                v-model.trim="inputContent.inputIdentifyCode"
              />
              <span class="span">
                <i class="el-icon-connection" style="font-size: 24px"></i>
              </span>
              <label class="label">请输入验证码</label>
            </div>
          </el-col>
          <el-col :span="10">
            <!-- 点击生成新的验证码 -->
            <div class="identifyCode-container" @click="refreshIdentifyCode">
              <s-identify :identifyCode="identifyCode"></s-identify>
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <!-- type=button阻止默认提交 -->
            <button type="button" class="button" @click="submitForm">
              登录
            </button>
          </el-col>
        </el-row>
        <div class="forgot-pass">
          <a href="#" @click="Find">已有账号，忘记密码?</a>
        </div>
      </form>
    </div>
    <div class="login-copyRight">
      <copy-right></copy-right>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
import SIdentify from "../components/identifyCode.vue";
import copyRight from "@/components/copyRight.vue";
import topBar from "@/components/topBar.vue";
import { Message } from "element-ui";
import { userLogin, getEncryptedAESKey } from "@/apis/apis";
import crypto from "@/utils/crypto";
import rsaEncrypt from "@/utils/rsaEncrypt";
@Component({
  name: "Login",
  components: {
    SIdentify,
    copyRight,
    topBar,
  },
})
export default class Login extends Vue {
  mounted() {
    // 页面加载时调用,初始化一次验证码
    this.refreshIdentifyCode();
  }

  Find(): void {
    //Message.warning("暂未设置找回，后续可以如果绑定邮箱可以发送账号");
    const route = this.$router.resolve({
      // 跳转到写审核列表页面
      path: "/FindPassword",
    });
    // 打开新页面
    window.open(route.href, "_blank");
  }

  // 定义输入内容的对象
  inputContent: {
    inputUserName: string;
    inputPassword: string;
    inputIdentifyCode: string;
  } = {
    inputUserName: "",
    inputPassword: "",
    inputIdentifyCode: "",
  };
  // 提交的表单数据
  submitFormData: {
    userName: string;
    password: string;
  } = {
    userName: "",
    password: "",
  };

  // 验证码与生成验证码的随机串
  identifyCode: string = "";
  identifyCodeRandom: string = "1234567890abcdefjhijklinopqrsduvwxyz";

  // 创建4位的验证码
  makeIdentifyCode(identifyCodeRandom: string, length: number): void {
    let identifyCode = "";
    let identifyCodeRandomLength = identifyCodeRandom.length;
    for (let i = 0; i < length; i++) {
      identifyCode +=
        identifyCodeRandom[
          Math.floor(Math.random() * identifyCodeRandomLength)
        ];
    }
    this.identifyCode = identifyCode;
    // 打印输出验证码
  }

  // 刷新验证码
  refreshIdentifyCode(): void {
    this.makeIdentifyCode(this.identifyCodeRandom, 4);
  }
  // 验证码输入判别
  identifyCodeJudge(): boolean {
    if (this.inputContent.inputIdentifyCode === this.identifyCode) {
      return true;
    } else {
      return false;
    }
  }
  // 验证码异常输入处理
  handleIdentifyCodeErrorInput(): void {
    Message({
      message: "验证码错误，请重新输入",
      type: "error",
    });
    // 刷新验证码
    this.refreshIdentifyCode();
  }

  // 提交表单
  async submitForm() {
    // 验证码在前端判别
    if (this.identifyCodeJudge()) {
      this.submitFormData.userName = this.inputContent.inputUserName;
      this.submitFormData.password = this.inputContent.inputPassword;
      getEncryptedAESKey()
        .then((res) => {
          if (res.data.code === "200") {
            let encryptedAESKey = res.data.data;
            // 调用rsa解密
            let decryptedAESKey = rsaEncrypt.decryptKey(
              encryptedAESKey
            ) as string;
            // 使用aes加密
            let encryptedPassword = crypto.encrypt(
              this.submitFormData.password,
              decryptedAESKey
            );
            this.submitFormData.password = encryptedPassword;
            userLogin(
              this.submitFormData.userName,
              this.submitFormData.password
            )
              .then((res) => {
                // 现在和后端联调使用的token直接是字符串，不用JSON。stringify
                if (res.data.code === "200") {
                  // 将token存入localStorage
                  localStorage.setItem("token", res.data.data.token);
                  // 将token存入vuex
                  this.$store.commit("setToken", res.data.data.token);
                  if (res.data.data.roleId === 0) {
                    this.$store.commit("setRoleName", "user");
                  } else if (res.data.data.roleId === 1) {
                    this.$store.commit("setRoleName", "auditor");
                  } else if (res.data.data.roleId === 2) {
                    this.$store.commit("setRoleName", "admin");
                  }
                  this.$store.commit("setAvatarUrl", res.data.data.avatar);
                  this.$store.commit("setNickName", res.data.data.nickName);
                  this.$store.commit("setUserId", res.data.data.userId);
                  // 先跳转再提示
                  this.$router.push("/userMain");
                  
                  Message.success("登录成功");
                } else {
                  Message.error("登录失败");
                }
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            this.$message.error("登录失败!请重试！");
            this.refreshIdentifyCode();
          }
        })
        .catch((err) => {
          this.$message.error("error,登录失败!请重试！");
          // 刷新验证码
          this.refreshIdentifyCode();
          console.log(err);
        });
    } else {
      // 重新刷新验证码
      this.handleIdentifyCodeErrorInput();
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: relative;
  // 云海
  background: url("../assets/login/background/Sea\ of\ Clouds-12.5s-2328px.svg")
    no-repeat center center fixed;
  // 条带
  // background: url("../assets/login/background/Valley-10s-1397px.svg") no-repeat center center fixed;
  background-size: cover;
  .login-topBar {
    position: absolute;
    box-sizing: border-box;
    top: 0;
    width: 100%;
  }
  .content {
    width: 330px;
    padding: 40px 25px;
    background: linear-gradient(#86c2f6, #99c4ea, #dfe5fb);
    // background: rgba(221, 225, 231, 0.5);
    border-radius: 10px;
    box-shadow: -3px -3px 7px #ffffff73, 2px 2px 5px rgba(94, 104, 121, 0.288);
    .text {
      font-size: 33px;
      font-weight: 600;
      margin-bottom: 35px;
      color: #595959;
      text-shadow: 2px 2px 5px #ffffff73,
        -2px -2px 5px rgba(94, 104, 121, 0.288);
    }
    // 设置表单项之间的间隔
    .el-row {
      margin-bottom: 15px;
      &:last-child {
        margin-bottom: 0;
      }
    }
    .field {
      height: 50px;
      width: 100%;
      display: flex;
      position: relative;
      .input {
        height: 100%;
        width: 100%;
        padding-left: 45px;
        outline: none;
        border: none;
        font-size: 18px;
        background: #dde1e7;
        opacity: 0.8;
        color: #181818;
        border-radius: 25px;
        box-shadow: inset 2px 2px 5px #babecc, inset -5px -5px 10px #ffffff73;
      }
      .input:focus {
        box-shadow: inset 1px 1px 2px #babecc, inset -1px -1px 2px #ffffff73;
      }

      .span {
        position: absolute;
        color: #595959;
        width: 50px;
        line-height: 55px;
      }
      .label {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        left: 45px;
        pointer-events: none;
        color: #666666;
      }
      .input:valid ~ label {
        opacity: 0;
      }
    }

    .forgot-pass {
      text-align: left;
      margin: 10px 0 10px 5px;
      a {
        font-size: 16px;
        color: #549ad8;
        text-decoration: none;
      }
    }

    .forgot-pass:hover a {
      text-decoration: underline;
    }

    .button {
      margin: 15px 0;
      width: 100%;
      height: 50px;
      font-size: 18px;
      line-height: 50px;
      font-weight: 600;
      background: linear-gradient(#dde1e7, #f7f5fd);
      opacity: 0.8;
      border-radius: 25px;
      border: none;
      outline: none;
      // 鼠标移入时的样式
      cursor: pointer;
      transition: transform 1s ease;
      color: #595959;
      box-shadow: 2px 2px 5px #babecc, -3px -3px 5px #e1e1e173;
    }

    .button:active {
      transform: scale(0.95);
      box-shadow: inset 2px 2px 5px #babecc, inset -5px -5px 10px #ffffff73;
    }
  }
  .login-copyRight {
    position: absolute;
    box-sizing: border-box;
    bottom: 0;
    width: 100%;
  }
}
</style>